#!/usr/bin/env node

const fs = require('fs')
const path = require('path')
const inquirer = require('inquirer')
const ejs = require('ejs')

const ncp = require('ncp').ncp

inquirer
  .prompt([
    {
      type: 'input',
      name: 'name',
      message: 'Project name'
    }, {
      type: 'list',
      name: 'framework',
      message: 'Framework?',
      choices: ['React', 'vue'],
      default: 'React'
    }, {
      type: 'list',
      name: 'automation',
      message: 'Automation?',
      choices: ['Gulp', 'Grunt'],
      default: 'Gulp'
    }
  ])
  .then(answers => {
    const {framework, automation} = answers

    const commonDir = path.join(__dirname, 'templates', 'common')
    const destDir = process.cwd()

    fs.readdir(commonDir, (err, files) => {
      if (err) throw err
      files.forEach(file => {
        ejs.renderFile(path.join(commonDir, file), answers, (err, result) => {
          if (err) throw err

          fs.writeFileSync(path.join(destDir, file), result)
        })
      })
    })

    let frameworkDir = path.join(__dirname, 'templates', 'react')
    if(framework === 'React'){
      frameworkDir = path.join(__dirname, 'templates', 'react')
    } else {
      frameworkDir = path.join(__dirname, 'templates', 'vue')
    }

    ncp(frameworkDir, destDir, function (err) {
      if (err) {
        return console.error(err);
      }
    })

    let automationFile = 'gulpfile.js'
    if(automation === 'Gulp'){
      automationFile = 'gulpfile.js'
    } else {
      automationFile = 'gruntfile.js'
    }
    fs.copyFile(path.join(__dirname, 'templates', automationFile), path.join(destDir, automationFile), (err) => {
      if (err) throw err;
    });
  })
  .catch(error => {
    if(error.isTtyError) {
      console.log('Inquirer error: prompt couldn\'t be rendered in the current environment')
    } else {
      console.log('Inquirer error: unexpected error')
    }
  });